import 'dart:async';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:word_range_client/viewModels/UserViewModel.dart';

import '../PadView.dart';
import '../PhoneView.dart';
import '../WindowsView.dart';

class AccountDeletionConfirmation extends StatefulWidget {
  const AccountDeletionConfirmation({super.key});

  @override
  State<AccountDeletionConfirmation> createState() => _AccountDeletionConfirmationState();
}

class _AccountDeletionConfirmationState extends State<AccountDeletionConfirmation> {
  bool _isButtonEnabled = false;
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    // 5秒后启用按钮
    _timer = Timer(const Duration(seconds: 5), () {
      setState(() {
        _isButtonEnabled = true;
      });
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    super.dispose();
  }

  void applyAccountDeletionConfirmation() async{
    // 弹窗二次确认
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('再次警告'),
          content: const Text('注销账户将永久删除所有数据且不可恢复，请确认是否继续？'),
          actions: <Widget>[
            TextButton(
              child: const Text('我点错了，取消这次操作'),
              onPressed: () {
                Navigator.of(context).pop();
              },
            ),
            TextButton(
              onPressed: () async {
                UserViewModel userViewModel = UserViewModel();
                userViewModel.deleteUser();
                Navigator.of(context).pop();
                final prefs = await SharedPreferences.getInstance();
                prefs.clear();
                _toWelcomePage();
                },
              child: const Text('我已了解风险，确定要消除账户所有信息'),
            )
          ]
        );
      }
    );
  }

  Future<void> _toWelcomePage() async {
    if(Platform.isAndroid){
      final bool isMobileLayout = MediaQuery.of(context).size.width < 600;
      if(isMobileLayout){
        Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => const PhoneView(isDarkMode: false)));
      }else{
        Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => const PadView(isDarkMode: false)));
      }
    }else{   // 目前只支持安卓、Windows
      Navigator.of(context).pushReplacement(MaterialPageRoute(builder: (context) => const WindowsView(isDarkMode: false)));
    }
    // 弹出通知
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return const AlertDialog(
          title: Text('已通知管理员清除账户使用痕迹，愿我们有缘再见！'),
        );
      }
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
            '账户注销确认',
            style: TextStyle(
              fontSize: 23,
              fontWeight: FontWeight.w500,
              color: Colors.white,
            ),
        ),
        backgroundColor: Theme.of(context).colorScheme.error,
      ),
      body: Hero(
          tag: "AccountDeletionConfirmation",
          child: Container(
            width: double.infinity,
            color: Theme.of(context).colorScheme.error,
            child: const _Body())
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
      floatingActionButton: SizedBox(
        width: MediaQuery.of(context).size.width * 0.85,
        child: FloatingActionButton(
          tooltip: '注销账户',
          onPressed: _isButtonEnabled
              ? () {
            // 执行销户操作
            applyAccountDeletionConfirmation(); // 返回上一页
          }
              : null,
          backgroundColor: _isButtonEnabled ? Colors.yellow : Colors.grey,
          child: Text(
            _isButtonEnabled ?
            "我已了解风险，确定消除账户所有信息":
            "请等待5秒，详细阅读上方文字",
            style: const TextStyle(
              fontSize: 17,
              color: Colors.red,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
      ),
    );
  }
}

class _Body extends StatelessWidget {
  const _Body({super.key});

  @override
  Widget build(BuildContext context) {
    return const Column(
      mainAxisAlignment: MainAxisAlignment.center,
      crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Text(
          "⚠️",
          style: TextStyle(
            fontSize: 80,
          ),
        ),
        Text(
            "警告",
            style: TextStyle(
              fontSize: 40,
              fontWeight: FontWeight.bold,
              color: Colors.yellow,
            )
        ),
        Text(
          '注销账户将永久删除所有数据且不可恢复',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.yellow,
          ),
          textAlign: TextAlign.center,
        ),
        Text(
          '请慎重考虑后继续',
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
            color: Colors.yellow,
          ),
          textAlign: TextAlign.center,
        )
      ],
    );
  }
}

